<template>
  <view>
    <view class="login">
      <view style="position: absolute;top: 10%;width: 100%;">
       <text class="text_4">WIFI信息</text>
      </view>
      <view class="wrap">
        <view style="display: flex;flex-direction: column;align-items: flex-end;width:  70vw;">
          <view style="display: flex;align-items: center;width: 100%">
<!--            <text>WIFI名：</text>-->
            <uni-easyinput class="input" v-model="localSSID" :inputBorder="true" maxlength="30"
                           placeholder="请输入WIFI名"></uni-easyinput>
          </view>
          <view style="display: flex;align-items: center;width:  100%">
            <!--            <text>密码：</text>-->
            <uni-easyinput class="input" v-model="localPassword" type="password" :inputBorder="true" :clearable="true"
                           placeholder="请输入WIFI密码"></uni-easyinput>
          </view>
        </view>
        <view class="button-group">
          <view class="button" @click="senCode">
            <text> 配 网</text>
          </view>
          <view class="button quick-connect" @click="quickConnect">
            <text>快 连</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import encoder from '@/static/libs/encoder.js'

export default {
  name: "bluewifi",
  props: {
    SSID: {
      type: String,
      default: ''
    },
    password: {
      type: String,
      default: ''
    },
    result: {
      type: Boolean,
      default: false
    },
    serialnum_equip: {
      type: String,
      default: ''
    },
    macAddress: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      currentIndex: 0,
      tabArr: [{
        name: '学生'
      }, {
        name: '教师'
      }],
      localSSID: this.SSID,   // 新增局部变量
      localPassword: this.password,  // 新增局部变量
      currentUser: '',
      deviceInfo: null,
      socketTask: null,
      is_open_socket: false
    };
  },
  created() {
    // 获取当前用户信息
    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      this.currentUser = userInfo.account;
      this.connectSocketInit();
    }
  },
  methods: {
    tabChange(index) {
      console.log('切换用户类型标签:', index);
      this.currentIndex = index;
    },

    senCode() {
      console.log('开始发送配网指令');
      if (!this.result) {
        console.warn('蓝牙未连接，无法配网');
        this.$api.msg('似乎没连上蓝牙设备');
        return;
      }

      if (this.localSSID !== '') {  // 使用局部变量
        uni.showLoading({
          title: '正在配网...',
          mask: true
        });

        console.log(encoder)
        var command = encoder.init()
        command.init()
        command.addCode(97);
        console.log('发送起始码 97,a,接受设备号');
        let data1 = command.getData()
        console.log('准备发送设备号获取数据:' + data1)
        this.$blueToothTool.sendByteData(data1)
        console.log('设备号获取数据发送完毕');
        command.init()
        let data2 = command.getData()
        console.log('初始化发送数据:' + data2);
        command.addCode(42);
        console.log('发送起始码 42');
        command.addString(this.localSSID);  // 使用局部变量
        console.log('添加SSID:' + this.localSSID);
        command.addCode(33);
        console.log('发送分隔符 33');
        command.addCode(40);
        console.log('发送括号开始 40');
        command.addString(this.localPassword);  // 使用局部变量
        console.log('添加密码:'+ this.localPassword);
        command.addCode(41);
        console.log('发送括号结束 41');
        let data = command.getData()
        console.log('准备发送配网数据:'+ data)
        this.$blueToothTool.sendByteData(data)
        console.log('发送完毕');
        
        // 通知父组件更新WiFi信息
        this.$emit('wifi-info-updated', {
          ssid: this.localSSID,
          password: this.localPassword
        });
      } else {
        console.warn('缺少WiFi信息或密码');
        this.$api.msg('没有WIFI信息？或密码');
        this.getWifiInfo();
      }
    },

    quickConnect() {
      console.log('开始发送快连指令');
      if (!this.result) {
        console.warn('蓝牙未连接，无法快连');
        this.$api.msg('似乎没连上蓝牙设备');
        return;
      }
      
      var command = encoder.init()
      command.init()
      command.addCode(64);  // 发送快连符号
      console.log('发送快连符号 @');
      let data = command.getData()
      console.log('发送快连数据');
      this.$blueToothTool.sendByteData(data)
      this.$api.msg('正在尝试快速连接...');
    },

    // WebSocket初始化
    connectSocketInit() {
      console.log('初始化WebSocket连接');
      this.socketTask = uni.connectSocket({
        url: 'ws://43.142.102.167:8088/woonsocket/' + this.currentUser,
        success(data) {
          console.log("websocket连接成功");
        },
      });
      
      this.socketTask.onOpen(() => {
        console.log("WebSocket连接正常打开中...！");
        this.is_open_socket = true;
      });
      
      this.socketTask.onMessage((res) => {
        console.log("收到服务器内容：", res.data);
        this.$api.msg(res.data);
      });
      
      this.socketTask.onClose(() => {
        console.log("WebSocket已经被关闭了");
        this.is_open_socket = false;
      });
    },
  },
  beforeDestroy() {
    if (this.socketTask) {
      this.socketTask.close();
    }
  }
}
</script>


<style lang="scss">
.text_4 {
		color: #000000;
		font-size: 36rpx;
		font-family: SourceHanSansCN;
		line-height: 47.92rpx;
		margin-top: 10rpx;
		margin-left: 47rpx;
	}
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 15px;
  height: 35vh;
  background-color: #fff;
  border-radius: 60rpx 60rpx 60rpx 60rpx;
  box-shadow: 0px 0px 20rpx 4rpx rgba(0, 0, 0, 0.40);

  .jump {
    position: absolute;
    top: 5%;
    right: 5%;
  }

  .wrap {
	margin-top: 80rpx;
    width: 70vw;
    height: auto;
    display: flex;
    align-items: center;
    flex-direction: column;

    .button-group {
      width: 80%;
      display: flex;
      flex-direction: column;
      gap: 20rpx;
      margin-top: 10rpx;
    }

    .button {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 80rpx;
      width: 100%;
      font-size: 32rpx;
      color: #fff;
      background-color: #138f87;
      border-radius: 500rpx;
      transition: all 0.3s;

      &:active {
        transform: scale(0.98);
        background-color: #1b78e9;
      }
    }

    .quick-connect {
      background-color: #4CAF50;
      
      &:active {
        background-color: #45a049;
      }
    }
  }
}
</style>